package com.epfresh.supplier.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.AppBarLayout.OnOffsetChangedListener;
import android.support.design.widget.TabLayout;
import android.support.design.widget.TabLayout.OnTabSelectedListener;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.epfresh.api.constant.AppSupplyRouterConstant;
import com.epfresh.api.entity.RequestEntity;
import com.epfresh.api.entity.RequestEntityMap;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.global.BaseApplication;
import com.epfresh.api.global.BaseFragment;
import com.epfresh.api.global.BuyerConstant;
import com.epfresh.api.helper.ApplicationHelper;
import com.epfresh.api.http.HttpRequest;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.JsonUtils;
import com.epfresh.api.utils.T;
import com.epfresh.api.widget.Dialog.BaseDialogView;
import com.epfresh.api.widget.MsgView;
import com.epfresh.api.widget.tablayout.utils.UnreadMsgUtils;
import com.epfresh.supplier.R;
import com.epfresh.supplier.activity.HomeActivity;
import com.epfresh.supplier.activity.MakeAgentActivity;
import com.epfresh.supplier.activity.OrderAgentActivity;
import com.epfresh.supplier.activity.OrderOnGroupActivity;
import com.epfresh.supplier.activity.WebActivity;
import com.epfresh.supplier.constant.Constant;
import com.epfresh.supplier.dialog.FilterCategoryDialog;
import com.epfresh.supplier.dialog.FilterCityDialog;
import com.epfresh.supplier.dialog.MerchantListDialog;
import com.epfresh.supplier.entity.BuyerFilter;
import com.epfresh.supplier.entity.HomeBuyerNumber;
import com.epfresh.supplier.entity.MerChantInfo;
import com.epfresh.supplier.entity.MerchantMember;
import com.epfresh.supplier.entity.StaffInfo;
import com.epfresh.supplier.entity.ZhDaiBanRedDotEntity;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Author: Chen
 * Date: 2018/6/27
 * Desc:
 */
public class HomeBuyerNewFragment extends BaseFragment implements FilterCityDialog.SelectCondition {
    public PingCheJinHuoFragment pingCheJinHuoFragment;
    public AgentMakeFragment agentMakeFragment;
    private AppBarLayout appBarLayout;
    private View toolbarTopLayout, toolbarBottomLayout, viewOver;
    private View middleLayout, city_category, city_category_2;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private String[] tabNames = {"拼车进货", "招代办"};
    private Toolbar toolbar;
    private int flag = 0;
    private final List<BaseFragment> fragmentList = new ArrayList<>();

    private ImageView iv_ping, iv_dai, iv_mine, iv_jin, iv_zh;
    private TextView tv_title, tv_order_together, tv_order_agent, tv_make_agent, txt_introduce,txt_introduce_pin;
    private MsgView msg_together, msg_agent;

    private View llCity, llCategory, llCity_2, llCategory_2;
    private TextView tvCity, tvCategory, tvCity_2, tvCategory_2;
    private ImageView ivCity, ivCategory, ivCity_2, ivCategory_2;
    private FilterCityDialog filterCityDialog,filterCityDialog_2;
    private FilterCategoryDialog filterCategoryDialog,filterCategoryDialog_2;
    private String cityName = "城市", categoryName = "品类";
    private String cityName_2 = "城市", categoryName_2 = "品类";
    private int dialogHeight = 0;
    private int select;

    private MerchantListDialog merchantListDialog;
    private ImageView ivFilter;
    private List<MerChantInfo> merChantInfoList = new ArrayList<>();

    @Override
    public String getBaseTag() {
        return Constant.TAG_HOME_FRAGMENT;
    }

    @Override
    public void selectCity(String condition, String name) {
        if (flag == 0) {
            cityName = name;
            pingCheJinHuoFragment.cityId = condition;
            pingCheJinHuoFragment.reqSupplyStoreDyn(0);
        }
        if (flag == 1) {
            cityName_2 = name;
            agentMakeFragment.cityId = condition;
            agentMakeFragment.reqSupplyStoreDyn(0);
        }
        commonDismiss();
    }

    @Override
    public void selectCategory(String condition, String name) {
        if (flag == 0) {
            categoryName = name;
            pingCheJinHuoFragment.categoryId = condition;
            pingCheJinHuoFragment.reqSupplyStoreDyn(0);
        }
        if (flag == 1) {
            categoryName_2 = name;
            agentMakeFragment.categoryiiiId = condition;
            agentMakeFragment.reqSupplyStoreDyn(0);
        }
        commonDismiss();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_home_buyer_new, container, false);
    }

    /**
     * 该方法在 onCreateView() 之后会被立即执行
     * 此时可以对 View 对象进行赋值，当然在 onCreateView() 中也可以执行
     *
     * @param view
     * @param savedInstanceState
     */
    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);
        initListener();
        requestMainCnt();
        reqMerchantList();
        reqRedDot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        getAppActivity().setSupportActionBar(toolbar);
    }

    private void initView(View view) {
        initMiddleView(view);
        toolbar = view.findViewById(R.id.home_buyer_toolbar);

        appBarLayout = view.findViewById(R.id.appbar_layout);
        toolbarTopLayout = view.findViewById(R.id.home_buyer_toolbar_top);
        toolbarBottomLayout = view.findViewById(R.id.home_buyer_toolbar_bottom);
        viewOver = view.findViewById(R.id.view_over);
        middleLayout = view.findViewById(R.id.layout_middle);
        tabLayout = view.findViewById(R.id.home_buyer_tab_layout);

        city_category = view.findViewById(R.id.home_buyer_city_category);
        llCity = view.findViewById(R.id.ll_city);
        llCategory = view.findViewById(R.id.ll_category);
        tvCity = view.findViewById(R.id.tv_city);
        ivCity = view.findViewById(R.id.iv_city);
        tvCategory = view.findViewById(R.id.tv_category);
        ivCategory = view.findViewById(R.id.iv_category);

        city_category_2 = view.findViewById(R.id.home_buyer_city_category_2);
        llCity_2 = view.findViewById(R.id.ll_city_2);
        llCategory_2 = view.findViewById(R.id.ll_category_2);
        tvCity_2 = view.findViewById(R.id.tv_city_2);
        ivCity_2 = view.findViewById(R.id.iv_city_2);
        tvCategory_2 = view.findViewById(R.id.tv_category_2);
        ivCategory_2 = view.findViewById(R.id.iv_category_2);

        iv_ping = view.findViewById(R.id.home_activity_toolbar_commodity_manage_img);
        iv_dai = view.findViewById(R.id.home_activity_toolbar_agent_manage_img);
        iv_mine = view.findViewById(R.id.home_activity_toolbar_income_img);
        iv_jin = view.findViewById(R.id.home_activity_toolbar_bellow_mine_img);
        iv_zh = view.findViewById(R.id.home_activity_toolbar_bellow_zh_img);

        tv_title = view.findViewById(R.id.home_activity_toolbar_upper_shop_name);
        ivFilter = view.findViewById(R.id.iv_filter);
        updateTitle();

        viewPager = view.findViewById(R.id.home_buyer_view_pager);
        viewPager.setAdapter(new TabFragmentPagerAdapter(getChildFragmentManager(), getFragmentList(), Arrays.asList(tabNames)));
        viewPager.setOffscreenPageLimit(2);
        //除了style样式也可以在代码中直接设置相关属性
//        tabLayout.setSelectedTabIndicatorHeight(dp2px(getAppActivity(), 3));
//        tabLayout.setSelectedTabIndicatorColor(Color.parseColor("#ff0000"));
//        tabLayout.setTabTextColors(Color.parseColor("#626262"), Color.parseColor("#ff0000"));
        tabLayout.setupWithViewPager(viewPager);

//        for (String tabName : tabNames) {
//            tabLayout.addTab(tabLayout.newTab().setText(tabName));
//        }

        for (int i = 0; i < tabNames.length; i++) {
            TabLayout.Tab tab = tabLayout.getTabAt(i);
            if (tab != null) {
                tab.setCustomView(R.layout.home_buyer_tab_title);
                TextView tabTitle = tab.getCustomView().findViewById(R.id.txt_tab_title);
                tabTitle.setText(tabNames[i]);
                tabTitle.setTag(i);
            }
        }
    }

    public void updateTitle() {
        tv_title.setText(BaseApplication.getInstance().getStoreName());
    }

    private void initMiddleView(View view) {
        tv_order_together = view.findViewById(R.id.tv_order_together);
        tv_order_agent = view.findViewById(R.id.tv_order_agent);
        tv_make_agent = view.findViewById(R.id.tv_make_agent);
        txt_introduce = view.findViewById(R.id.txt_introduce);
        txt_introduce_pin = view.findViewById(R.id.txt_introduce_pin);
        msg_together = view.findViewById(R.id.msg_together);
        msg_agent = view.findViewById(R.id.msg_agent);
    }

    private void initListener() {
        appBarLayout.addOnOffsetChangedListener(offsetChangeListener);
        tabLayout.addOnTabSelectedListener(tabSelectedListener);
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

        tv_order_together.setOnClickListener(this);
        tv_order_agent.setOnClickListener(this);
        tv_make_agent.setOnClickListener(this);
        txt_introduce.setOnClickListener(this);
        txt_introduce_pin.setOnClickListener(this);

        llCity.setOnClickListener(this);
        llCategory.setOnClickListener(this);
        llCity_2.setOnClickListener(this);
        llCategory_2.setOnClickListener(this);
        tv_title.setOnClickListener(this);

        iv_ping.setOnClickListener(this);
        iv_dai.setOnClickListener(this);
        iv_mine.setOnClickListener(this);
        iv_jin.setOnClickListener(this);
        iv_zh.setOnClickListener(this);
    }

    public static int dp2px(Context context, float dpValue) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpValue, context.getResources().getDisplayMetrics());
    }

    OnTabSelectedListener tabSelectedListener = new OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            if (tabLayout.getTabAt(1).getCustomView().findViewById(R.id.zhao_dai_ban_dot).getVisibility() == View.VISIBLE) {
                tabLayout.getTabAt(1).getCustomView().findViewById(R.id.zhao_dai_ban_dot).setVisibility(View.GONE);
            }
            if (redDotRefreshTime != 0) {
                ApplicationHelper.getInstance().setDotRefreshTime(redDotRefreshTime);
            }
            Log.i("hello", tab.getPosition() + "");
            if (tab.getPosition() == 0) {
                if (isShrink) {
                    city_category.setVisibility(View.VISIBLE);
                    city_category_2.setVisibility(View.GONE);
                }
                flag = 0;
                iv_jin.setVisibility(View.GONE);
                iv_zh.setVisibility(View.VISIBLE);
            } else if (tab.getPosition() == 1) {
                if (isShrink) {
                    city_category.setVisibility(View.GONE);
                    city_category_2.setVisibility(View.VISIBLE);
                }
                flag = 1;
                iv_jin.setVisibility(View.VISIBLE);
                iv_zh.setVisibility(View.GONE);
            }
            viewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    };

    OnOffsetChangedListener offsetChangeListener = new OnOffsetChangedListener() {
        @Override
        public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
            int offset = Math.abs(verticalOffset);
            int total = appBarLayout.getTotalScrollRange();
            float ratio = 1 - Math.abs(offset) * 1.0f / total;
            ratio = constrain(ratio, 0, 1);

            float alpha1 = 1 - Math.min(1, ratio / 0.5f);
            float alpha2 = Math.max((ratio - 0.5f) / 0.5f, 0);
            float alpha3 = 1 - Math.abs(offset) * 1.f / (0.65f * appBarLayout.getHeight());
            alpha3 = constrain(alpha3, 0, 1);

            toolbarTopLayout.setAlpha(alpha2);

            toolbarBottomLayout.setAlpha(alpha1);
            middleLayout.setAlpha(alpha3);

            if (offset <= total / 2) {
                toolbarTopLayout.setVisibility(View.VISIBLE);
                toolbarBottomLayout.setVisibility(View.GONE);
            } else {
                toolbarTopLayout.setVisibility(View.GONE);
                toolbarBottomLayout.setVisibility(View.VISIBLE);
            }
            if (offset == 0) {
                isShrink = false;
                //完全展开
                tabLayout.setVisibility(View.VISIBLE);
                if (flag == 0) {
                    city_category.setVisibility(View.GONE);
                } else if (flag == 1) {
                    city_category_2.setVisibility(View.GONE);
                }
                PingCheJinHuoFragment.isCanRefresh = true;
                AgentMakeFragment.isCanRefresh = true;
            } else {
                PingCheJinHuoFragment.isCanRefresh = false;
                AgentMakeFragment.isCanRefresh = false;
            }
            if (offset == total) {
                isShrink = true;
                //完全收缩
                tabLayout.setVisibility(View.GONE);
                if (flag == 0) {
                    city_category.setVisibility(View.VISIBLE);
                } else if (flag == 1) {
                    city_category_2.setVisibility(View.VISIBLE);
                }

                dialogHeight = viewOver.getBottom() / 2 + dp2px(getAppActivity(), 15);

            }
        }
    };

    private boolean isShrink = false;

    public float constrain(float ratio, float low, float high) {
        float ratio_act = ratio < low ? low : ratio;
        ratio_act = ratio_act > high ? high : ratio_act;
        return ratio_act;
    }

    class TabFragmentPagerAdapter extends FragmentPagerAdapter {
        private List<BaseFragment> fragmentList;
        private List<String> tabNames;

        public TabFragmentPagerAdapter(FragmentManager fm, List<BaseFragment> fragmentList, List<String> tabNames) {
            super(fm);
            this.fragmentList = fragmentList;
            this.tabNames = tabNames;
        }

        @Override
        public Fragment getItem(int position) {
            return fragmentList == null ? null : fragmentList.get(position);
        }

        @Override
        public int getCount() {
            return fragmentList.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return tabNames.get(position);
        }
    }

    private List<BaseFragment> getFragmentList() {
        fragmentList.clear();
        pingCheJinHuoFragment = new PingCheJinHuoFragment();
        agentMakeFragment = new AgentMakeFragment();
        fragmentList.add(pingCheJinHuoFragment);
        fragmentList.add(agentMakeFragment);
        return fragmentList;
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.tv_order_together://拼货订单
                intent = new Intent(getAppActivity(), OrderOnGroupActivity.class);
                intent.putExtra("orderType", 0);
                startActivity(intent);
                break;
            case R.id.tv_order_agent://代办订单
                intent = new Intent(getAppActivity(), OrderAgentActivity.class);
                intent.putExtra("orderType", 1);
                startActivity(intent);
                break;
            case R.id.tv_make_agent://我的代办
                intent = new Intent(getAppActivity(), MakeAgentActivity.class);
                startActivity(intent);
                break;
            case R.id.txt_introduce:
                intent = new Intent(getContext(), WebActivity.class);
                intent.putExtra(Constant.KEY_WEB_URL, Constant.URL_HELP_BUYER_HOME);
                intent.putExtra(Constant.KEY_WEB_TITLE, getString(R.string.help));
                startActivity(intent);
                break;
            case R.id.txt_introduce_pin:
                intent = new Intent(getContext(), WebActivity.class);
                intent.putExtra(Constant.KEY_WEB_URL, Constant.URL_HELP_BUYER_HOME);
                intent.putExtra(Constant.KEY_WEB_TITLE, getString(R.string.help));
                startActivity(intent);
                break;
            case R.id.ll_city:
                select = 0;//打开城市筛选弹窗
                reqHomePageProductFilter(0);
                break;
            case R.id.ll_category:
                select = 1;//打开品类筛选弹窗
                reqHomePageProductFilter(0);
                break;
            case R.id.ll_city_2:
                select = 0;
                reqHomePageProductFilter(1);
                break;
            case R.id.ll_category_2:
                select = 1;
                reqHomePageProductFilter(1);
                break;

            case R.id.home_activity_toolbar_upper_shop_name:
                expendTitle();
                txt_introduce.setVisibility(View.INVISIBLE);
                break;

            case R.id.home_activity_toolbar_commodity_manage_img:
                intent = new Intent(getAppActivity(), OrderOnGroupActivity.class);
                intent.putExtra("orderType", 0);
                startActivity(intent);
                break;

            case R.id.home_activity_toolbar_agent_manage_img:
                intent = new Intent(getAppActivity(), OrderAgentActivity.class);
                intent.putExtra("orderType", 1);
                startActivity(intent);
                break;

            case R.id.home_activity_toolbar_income_img:
                intent = new Intent(getAppActivity(), MakeAgentActivity.class);
                startActivity(intent);
                break;

            case R.id.home_activity_toolbar_bellow_mine_img:
                viewPager.setCurrentItem(0, true);
                break;

            case R.id.home_activity_toolbar_bellow_zh_img:
                viewPager.setCurrentItem(1, true);
                break;

        }
    }

    private void commonDismiss() {
        if (filterCityDialog != null)
            filterCityDialog.dismiss();
        if (filterCategoryDialog != null)
            filterCategoryDialog.dismiss();
        if (filterCityDialog_2 != null)
            filterCityDialog_2.dismiss();
        if (filterCategoryDialog_2 != null)
            filterCategoryDialog_2.dismiss();
    }

    private void openCityDialog(BuyerFilter buyerFilter) {
        if (buyerFilter == null) {
            T.toast("没有加载到筛选信息，请刷新后重试");
            return;
        }
        if (filterCityDialog == null) {
            filterCityDialog = new FilterCityDialog(getContext());
            filterCityDialog.setOnDismissListener(new BaseDialogView.OnDismissListener() {
                @Override
                public void onDismiss(Object o) {
                    tvCity.setTextColor(Color.parseColor("#434343"));
                    tvCity.setText(cityName);
                    ivCity.setImageResource(R.mipmap.select_down);
                }
            });
            filterCityDialog.setSelectCondition(this);
            tvCity.setTextColor(Color.RED);
            ivCity.setImageResource(R.mipmap.select_up);
            filterCityDialog.show(buyerFilter.getCities(), dialogHeight);
        } else {
            if (filterCityDialog.isShowing()) {
                filterCityDialog.dismiss();
            } else {
                filterCityDialog.show(buyerFilter.getCities(), dialogHeight);
                filterCityDialog.setCitySelect(cityName);
                tvCity.setTextColor(Color.RED);
                ivCity.setImageResource(R.mipmap.select_up);
            }
        }
    }

    private void openCityDialog_2(BuyerFilter buyerFilter) {
        if (buyerFilter == null) {
            T.toast("没有加载到筛选信息，请刷新后重试");
            return;
        }
        if (filterCityDialog_2 == null) {
            filterCityDialog_2 = new FilterCityDialog(getContext());
            filterCityDialog_2.setOnDismissListener(new BaseDialogView.OnDismissListener() {
                @Override
                public void onDismiss(Object o) {
                    tvCity_2.setTextColor(Color.parseColor("#434343"));
                    tvCity_2.setText(cityName_2);
                    ivCity_2.setImageResource(R.mipmap.select_down);
                }
            });
            filterCityDialog_2.setSelectCondition(this);
            tvCity_2.setTextColor(Color.RED);
            ivCity_2.setImageResource(R.mipmap.select_up);
            filterCityDialog_2.show(buyerFilter.getCities(), dialogHeight);
        } else {
            if (filterCityDialog_2.isShowing()) {
                filterCityDialog_2.dismiss();
            } else {
                filterCityDialog_2.show(buyerFilter.getCities(), dialogHeight);
                filterCityDialog_2.setCitySelect(cityName_2);
                tvCity_2.setTextColor(Color.RED);
                ivCity_2.setImageResource(R.mipmap.select_up);
            }
        }
    }

    private void openCategoryDialog(BuyerFilter buyerFilter) {
        if (buyerFilter == null) {
            T.toast("没有加载到筛选信息，请刷新后重试");
            return;
        }
        if (filterCategoryDialog == null) {
            filterCategoryDialog = new FilterCategoryDialog(getContext());
            filterCategoryDialog.setOnDismissListener(new BaseDialogView.OnDismissListener() {
                @Override
                public void onDismiss(Object o) {
                    tvCategory.setTextColor(Color.parseColor("#434343"));
                    tvCategory.setText(categoryName);
                    ivCategory.setImageResource(R.mipmap.select_down);
                }
            });
            tvCategory.setTextColor(Color.RED);
            ivCategory.setImageResource(R.mipmap.select_up);
            filterCategoryDialog.setSelectCondition(this);
            filterCategoryDialog.show(buyerFilter.getNames(), dialogHeight);
        } else {
            if (filterCategoryDialog.isShowing()) {
                filterCategoryDialog.dismiss();
            } else {
                tvCategory.setTextColor(Color.RED);
                ivCategory.setImageResource(R.mipmap.select_up);
                filterCategoryDialog.show(buyerFilter.getNames(), dialogHeight);
                filterCategoryDialog.setCategorySelect(categoryName);
            }
        }
    }

    private void openCategoryDialog_2(BuyerFilter buyerFilter) {
        if (buyerFilter == null) {
            T.toast("没有加载到筛选信息，请刷新后重试");
            return;
        }
        if (filterCategoryDialog_2 == null) {
            filterCategoryDialog_2 = new FilterCategoryDialog(getContext());
            filterCategoryDialog_2.setOnDismissListener(new BaseDialogView.OnDismissListener() {
                @Override
                public void onDismiss(Object o) {
                    tvCategory_2.setTextColor(Color.parseColor("#434343"));
                    tvCategory_2.setText(categoryName_2);
                    ivCategory_2.setImageResource(R.mipmap.select_down);
                }
            });
            tvCategory_2.setTextColor(Color.RED);
            ivCategory_2.setImageResource(R.mipmap.select_up);
            filterCategoryDialog_2.setSelectCondition(this);
            filterCategoryDialog_2.show(buyerFilter.getNames(), dialogHeight);
        } else {
            if (filterCategoryDialog_2.isShowing()) {
                filterCategoryDialog_2.dismiss();
            } else {
                tvCategory_2.setTextColor(Color.RED);
                ivCategory_2.setImageResource(R.mipmap.select_up);
                filterCategoryDialog_2.show(buyerFilter.getNames(), dialogHeight);
                filterCategoryDialog_2.setCategorySelect(categoryName_2);
            }
        }
    }

    public void requestMainCnt() {
        RequestEntity<Map<String, String>> entity = new RequestEntity<>();
        entity.setCmd("pm-order/baseorder/order/mainCnt");
        Map<String, String> map = new HashMap<>();
        map.put("buyerStoreId", BaseApplication.getInstance().getStoreId());
        entity.setParameters(map);
        request(entity, "pm-order/baseorder/order/mainCnt", onRequestListener);
    }

    OnRequestListener<HomeBuyerNumber> onRequestListener = new OnRequestListener<HomeBuyerNumber>() {
        @Override
        public HomeBuyerNumber jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, HomeBuyerNumber.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            Log.e(arg + "", "" + HttpRequest.FAIL_NET_FAULT);
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            Log.e(arg + "", "" + HttpRequest.FAIL_NET_FAULT);
        }

        @Override
        public void onStart(Object tag) {
        }

        @Override
        public void onResponse(ResponseEntity<HomeBuyerNumber> response, Object tag) {
            hideProgressDialog();
            HomeBuyerNumber responseElement = response.getResponseElement();

            if (responseElement.getGrouponCnt() == null || responseElement.getGrouponCnt() == 0) {
                msg_together.setVisibility(View.GONE);
            } else {
                msg_together.setVisibility(View.VISIBLE);
                UnreadMsgUtils.show(msg_together,responseElement.getGrouponCnt(),true,true);
//                msg_together.setText("" + responseElement.getGrouponCnt());
            }
            if (responseElement.getOrderCnt() == null || responseElement.getOrderCnt() == 0) {
                msg_agent.setVisibility(View.GONE);
            } else {
                msg_agent.setVisibility(View.VISIBLE);
                UnreadMsgUtils.show(msg_agent,responseElement.getOrderCnt(),true,true);
//                msg_agent.setText("" + responseElement.getOrderCnt());
            }
        }
    };

    /**
     * 我要买商品筛选条件
     * 12.20
     */
    private void reqHomePageProductFilter(int filter) {
        if (getActivity() == null) {
            return;
        }

        RequestEntityMap requestEntityMap = new RequestEntityMap();
//        requestEntityMap.setCmd("buy/homepage/filters");
        requestEntityMap.setCmd(BuyerConstant.CMD_BUYER_HOMEPAGE_FILTERS);
        requestEntityMap.putParameter("all", filter);
        requestEntityMap.putParameter("agentStoreId", BaseApplication.getInstance().getStoreId());
        requestBuyer(requestEntityMap, BuyerConstant.CMD_BUYER_HOMEPAGE_FILTERS, onSupplyFilterRequestListener);
    }

    private OnRequestListener<BuyerFilter> onSupplyFilterRequestListener = new OnRequestListener<BuyerFilter>() {
        @Override
        public BuyerFilter jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, BuyerFilter.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
        }

        @Override
        public void onStart(Object tag) {
        }

        @Override
        public void onResponse(ResponseEntity<BuyerFilter> response, Object tag) {
            if (getActivity() == null) {
                return;
            }
            BuyerFilter buyerFilter = response.getResponseElement();

            //本地手动添加城市"全部"选项的假数据
            BuyerFilter.CitiesBean citiesBean = new BuyerFilter.CitiesBean();
            citiesBean.setCode("");
            citiesBean.setName("全部");
            citiesBean.setSelectFlag(false);
            buyerFilter.getCities().add(0, citiesBean);

            //手动添加品类"全部"选项假数据
            BuyerFilter.NamesBean namesBean = new BuyerFilter.NamesBean();
            namesBean.setName("");
            namesBean.setId("");

            List<BuyerFilter.NamesBean.ChildBean> child = new ArrayList<>();
            BuyerFilter.NamesBean.ChildBean childBean = new BuyerFilter.NamesBean.ChildBean();
            childBean.setId("");
            childBean.setName("全部");
            childBean.setSelectFlag(false);
            child.add(childBean);

            namesBean.setChild(child);
            buyerFilter.getNames().add(0, namesBean);
            commonDismiss();
            if (select == 0) {
                if (flag == 0) {
                    openCityDialog(buyerFilter);
                } else if (flag == 1) {
                    openCityDialog_2(buyerFilter);
                }
            }
            if (select == 1) {
                if (flag == 0) {
                    openCategoryDialog(buyerFilter);
                } else if (flag == 1) {
                    openCategoryDialog_2(buyerFilter);
                }
            }
        }
    };

    private void expendTitle() {
        if (ivFilter.getVisibility() != View.VISIBLE) {
            return;
        }

        if (merchantListDialog == null) {
            merchantListDialog = new MerchantListDialog(getContext());
            merchantListDialog.setOnDismissListener(new BaseDialogView.OnDismissListener() {
                @Override
                public void onDismiss(Object o) {
                    updateTitleFlag(false);
                    txt_introduce.setVisibility(View.VISIBLE);
                }
            });
            merchantListDialog.setOnMerchantSwitch(new MerchantListDialog.OnMerchantSwitch() {
                @Override
                public void onMerchant(MerChantInfo merChantInfo) {
                    String name = merChantInfo.getNamePlus();
                    tv_title.setText(name);
                    updateTitleFlag(false);
                    BaseApplication.getInstance().putMerchant(merChantInfo);
                    requestMainCnt();
                    if (pingCheJinHuoFragment != null) {
                        pingCheJinHuoFragment.reqSupplyStoreDyn(0);
                    }
                    if (agentMakeFragment != null) {
                        agentMakeFragment.reqSupplyStoreDyn(0);
                    }
                    updateLoadToolbarTitle();
//                    initNotice();//提示变价更新的对话框以及红点

                    reqMerchantList();
                }
            });
        }

        if (merchantListDialog.isShowing()) {
            merchantListDialog.dismiss();
            updateTitleFlag(false);
        } else {
            merchantListDialog.show(merChantInfoList);
            updateTitleFlag(true);
        }

    }

    private void updateLoadToolbarTitle() {
        FragmentActivity activity = getActivity();
        if (activity != null && activity instanceof HomeActivity) {
          //  ((HomeActivity) activity).updateBuyerStatus();
        }
    }

    public void updateTitleFlag(boolean isExpend) {
        if (isExpend) {
            ivFilter.setImageResource(R.mipmap.icon_home_down);
        } else {
            ivFilter.setImageResource(R.mipmap.icon_home_up);
        }
    }

    public void reqMerchantList() {

        if (getActivity() == null) {
            return;
        }
//        updateTopInit();
        RequestEntityMap requestEntityMap = new RequestEntityMap();
        requestEntityMap.setCmd(AppSupplyRouterConstant.cmd_account_merchant_afterLogin);

        request(requestEntityMap, AppSupplyRouterConstant.cmd_account_merchant_afterLogin, onMerchantRequestListener);
    }

    private OnRequestListener<List<MerChantInfo>> onMerchantRequestListener = new OnRequestListener<List<MerChantInfo>>() {
        @Override
        public List<MerChantInfo> jsonToObj(String responseStr) {
            MerchantMember merchantMember = JsonUtils.fromJson(responseStr, MerchantMember.class);
            ArrayList<String> disabledResources = null;
            List<MerChantInfo> mcis = new ArrayList<MerChantInfo>();
            if (merchantMember != null) {
                List<StaffInfo> list = merchantMember.getEmployees();
                disabledResources = merchantMember.getDisabledResources();

                if (list != null)
                    for (int i = 0; i < list.size(); i++) {
                        StaffInfo staffInfo = list.get(i);
                        if (staffInfo != null) {
                            MerChantInfo mc = staffInfo.getMerchant();
                            if (mc != null) {
                                staffInfo.setMerchant(null);

                                mc.setStaffInfo(staffInfo);
                                if (mc.isOwned()) {
                                    mc.setDisabledResources(disabledResources);
                                }
                                mcis.add(mc);
                            }
                        }
                    }

            }

            BaseApplication.getInstance().updateMerchants(mcis);
            BaseApplication.getInstance().putMerchantDisabledResources(disabledResources);
            return mcis;
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            if (getActivity() == null) {
                return;
            }
//            ptrFrameLayout.refreshComplete();

        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            if (getActivity() == null) {
                return;
            }
//            ptrFrameLayout.refreshComplete();

        }

        @Override
        public void onStart(Object tag) {
        }

        @Override
        public void onResponse(ResponseEntity<List<MerChantInfo>> response, Object tag) {
            if (getActivity() == null) {
                return;
            }
//            ptrFrameLayout.refreshComplete();
            List<MerChantInfo> responseElement = response.getResponseElement();
            merChantInfoList.clear();
            if (responseElement != null)
                merChantInfoList.addAll(responseElement);

//            updateLoadToolbarTitle();
//            Log.e("first_________", "" +
//                    "" + BaseApplication.getInstance().getStoreId());
//            initNotice();//提示变价更新的对话框以及红点
//
//            mItems.clear();
//            mItems.add(new Integer(0));
//            for(int i=mAuthStatuses.size()-1;i>0;i--){
//                if (mAuthStatuses.get(i).getKey()=="root.app.supplier.buy"||mAuthStatuses.get(i).getKey()=="root.app.supplier.sell"||mAuthStatuses.get(i).getKey()=="root.app.supplier.store.decoration"||mAuthStatuses.get(i).getKey()=="root.app.supplier.product.purchase")
//                    mAuthStatuses.remove(i);
//            }
//            mItems.addAll(mAuthStatuses);
//            loadMoreDelegate.addAllItem(mItems, mOrderStoreDyns);
////            if (mOrderStoreDyns.size() == 0){
////                loadMoreDelegate.setStatusLoading();
////            }
//            mMultiAdapter.notifyDataSetChanged();
//            reqSupplyStoreDyn(0);

        }
    };

    /**
     * 招代办小红点
     */
    public void reqRedDot() {
        if (getActivity() == null)
            return;

        RequestEntityMap requestEntityMap = new RequestEntityMap();
        requestEntityMap.setCmd(BuyerConstant.CMD_ZHAO_DAI_BAN_RED_DOT);
        requestEntityMap.putParameter("storeId", BaseApplication.getInstance().getStoreId());
        requestBuyer(requestEntityMap, BuyerConstant.CMD_ZHAO_DAI_BAN_RED_DOT, redDotListener);
    }

    private OnRequestListener<ZhDaiBanRedDotEntity> redDotListener = new OnRequestListener<ZhDaiBanRedDotEntity>() {
        @Override
        public ZhDaiBanRedDotEntity jsonToObj(String responseStr) {
            return JsonUtils.fromJson(responseStr, ZhDaiBanRedDotEntity.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
        }

        @Override
        public void onStart(Object tag) {

        }

        @Override
        public void onResponse(ResponseEntity<ZhDaiBanRedDotEntity> response, Object tag) {
            if (response.getResponseElement() == null) {
                tabLayout.getTabAt(1).getCustomView().findViewById(R.id.zhao_dai_ban_dot).setVisibility(View.GONE);
            } else {
                redDotRefreshTime = response.getResponseElement().getMax();
                isShowDotZhDaiBan();
            }
        }
    };

    private long redDotRefreshTime;

    /**
     * 根据后台是所传事件跟本地存储的时间对比判断是否有新的代办事件
     */
    private void isShowDotZhDaiBan() {
        long dotRefreshTime = ApplicationHelper.getInstance().getDotRefreshTime();
        long l = redDotRefreshTime - dotRefreshTime;
        if (l > 0) {
            tabLayout.getTabAt(1).getCustomView().findViewById(R.id.zhao_dai_ban_dot).setVisibility(View.VISIBLE);
        } else {
            tabLayout.getTabAt(1).getCustomView().findViewById(R.id.zhao_dai_ban_dot).setVisibility(View.GONE);
        }

    }

}
